package cn.ycc1.service;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消费者类，用于接收消息
 * 注意：Topic 模式下，消息只会发给订阅时的消费者，之前的消息不会被接收。
 */
public class Consumer {
    private static final String BROKER_URL = "tcp://localhost:61616";
    private static final String QUEUE_NAME = "DEMO_QUEUE";

    public static void main(String[] args) {
        try {
            // 1. 创建连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);

            // 2. 创建连接
            Connection connection = connectionFactory.createConnection();
            connection.start();

            // 3. 创建会话
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // 4. 创建目标队列
//            Destination destination = session.createQueue(QUEUE_NAME);
            // 将 createQueue 改为 createTopic
            Destination destination = session.createTopic("DEMO_TOPIC");

            // 5. 创建消费者
            MessageConsumer consumer = session.createConsumer(destination);

            // 6. 设置消息监听器
            consumer.setMessageListener(message -> {
                try {
                    if (message instanceof TextMessage) {
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println("接收到消息: " + textMessage.getText());
                    }
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            });

            // 保持程序运行，持续接收消息
            System.out.println("消费者已启动，等待接收消息...");
            System.in.read(); // 按任意键退出

            // 7. 关闭连接
            session.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
